$(document).ready(function() {
	console.log("index page");
	$('.action .btn').on('click', on_action_button_clicked);
	$('.profile').on('click', on_profile_clicked);
	show_profile();
	show_trays();
	init_info();
	init_websocket();
} );



/*
    It enables/disables the buttons of action by status
    status is a string, can be such values:
        standby, running, paused, error
    buttons are:
        开始, 暂停, 继续, 停止

Well done! You successfully read this important alert message.
*/
function on_status_changed(status)
{
    var btns = null;
    if( status == 'standby' ){
        btns = [true, false, false, false];
    }
    else if( status == 'running'){
        btns = [false, true, false, true];
    }
    else if( status == 'paused'){
        btns = [false, false, true, true];
    }
    else if( status == 'error'){
        btns = [true, false, false, false];
    }
    else{
        return;
    }
    $('.action .btn').each(function(idx, item, arr){
        console.log(item);
        if( btns[idx] ){
            item.removeAttribute('disabled');
        }
        else{
            item.setAttribute('disabled', 'disabled');
        }
    });
}

function on_action_button_clicked(e)
{
    console.log(e.target.innerText);
    $.ajax({ url: "/running/button/click?what=" +e.target.innerText, success: function(html){
        var e = document.getElementsByClassName('profile')[0];
        e.innerHTML = html;
    }});
}

function on_profile_clicked(e)
{
    // console.log(e.target.innerText);
    window.location.href = '/running/profile/load';
}

/*
* load profile by ajax method
*/
function show_profile()
{
    $.ajax({ url: "/running/profile/detail", success: function(html){
        var e = document.getElementsByClassName('profile')[0];
        e.innerHTML = html;
    }});
}

/*
* load trays info by ajax method
*/
function show_trays()
{
    $.ajax({ url: "/running/trays", success: function(html){
        var e = document.getElementById('trays');
        e.innerHTML = html;
    }});
}

function init_info()
{
    $.ajax({ url: "/running/info", success: function(html){
        show_info(JSON.parse(html));
    }});
}
function show_info(info)
{
    var alert = document.getElementById('alert');
    if( info.title ){
        var h3 = alert.firstElementChild;
        h3.innerText = info.title;
    }
    if( info.msg ){
        var div = alert.lastElementChild;
        div.innerHTML = info.msg
    }

    if( info.clazz ){
        alert.className = alert.className.replace(/alert\-\S+/, 'alert-'+info.clazz)
    }
}


function init_websocket(){
    var socket = io.connect('http://' + document.domain + ':' + location.port);
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I\'m connected!'});
    });
    socket.on("info", function(info){
        show_info(info);
    });
}